<template>
  <div class="login-container">
    <div v-if="!store.isLoggedIn" class="login-form">
      <h2>用户登录</h2>
      <input type="text" v-model="username" placeholder="用户名 (admin)" />
      <input type="password" v-model="password" placeholder="密码 (123456)" />
      <button @click="login" :disabled="loading">
        {{ loading ? '登录中...' : '登录' }}
      </button>
    </div>
    <div v-else class="logout-section">
      <p>已登录成功</p>
      <button class="logout-btn" @click="handleLogout">退出登录</button>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { userLoginService } from '../api/user'
import { useCounterStore } from '../stores/counter'

const store = useCounterStore()
const username = ref('')
const password = ref('')
const loading = ref(false)

// 登录处理
const login = async () => {
  if (!username.value || !password.value) {
    console.warn('⚠️ 请输入用户名和密码')
    return
  }

  console.log('🔑 开始登录请求...')
  console.log('📤 发送数据:', {
    username: username.value,
    password: password.value
  })

  loading.value = true
  try {
    const res = await userLoginService({
      username: username.value,
      password: password.value
    })
    console.log('📨 登录接口返回数据:', res.data)

    if (res.data.code === 200) {
      console.log('✅ 登录成功，获取到 token')
      localStorage.setItem('token', res.data.data.token)
      store.setLoginState(true) // 更新登录状态

      console.log('📝 开始获取文章数据...')
      await store.getArticleList()

      username.value = ''
      password.value = ''
      console.log('✨ 登录流程完成')
    } else {
      console.warn('⚠️ 登录失败:', res.data.message)
      alert(res.data.message || '登录失败')
    }
  } catch (error) {
    console.error('❌ 登录出错:', error)
    alert('登录失败，请重试')
  } finally {
    loading.value = false
  }
}

// 退出登录处理
const handleLogout = () => {
  console.log('🚪 开始退出登录...')

  // 清除 token
  localStorage.removeItem('token')
  console.log('🗑️ token 已清除')

  // 清除 pinia 数据并更新状态
  store.removeArticleList()
  console.log('🗑️ pinia 数据已清除')

  console.log('✅ 退出登录完成')
}
</script>

<style scoped>
.login-container {
  padding: 20px;
  text-align: center;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  max-width: 400px;
  margin: 50px auto;
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.logout-section {
  padding: 20px;
}

.logout-section p {
  margin-bottom: 15px;
  color: #4caf50;
}

input {
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  transition: border-color 0.3s;
}

input:focus {
  border-color: #4caf50;
  outline: none;
}

button {
  padding: 10px;
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #45a049;
}

button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.logout-btn {
  background-color: #f44336;
}

.logout-btn:hover {
  background-color: #d32f2f;
}
</style>
